
package com.android.finaltracer.servercall;

import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author guhl1
 * @param <K>
 * @param <V>
 */
public class SequenceHashmap<K, V> extends HashMap<K, V> {

    /**
	 * 
	 */
    private static final long serialVersionUID = 689069676839287061L;

    private List<K> keys = new ArrayList<K>();

    private KeySet keySet;

    @Override
    public V put(K key, V value) {
        if (keys.indexOf(key) == -1) {
            keys.add(key);
        }
        return super.put(key, value);
    }

    @Override
    public Set<K> keySet() {
        if (keySet == null) {
            keySet = new KeySet();
        }
        return keySet;
    }

    @Override
    public void clear() {
        super.clear();
        keys.clear();
    }

    @Override
    public V remove(Object key) {
        keys.remove(key);
        return super.remove(key);
    }

    private final class KeySet extends AbstractSet<K> {

        @Override
        public Iterator<K> iterator() {
            return keys.iterator();
        }

        @Override
        public int size() {
            return keys.size();
        }

        @Override
        public void clear() {
            super.clear();
            SequenceHashmap.this.clear();
        }

        @Override
        public boolean isEmpty() {
            return keys.size() == 0;
        }

        @Override
        public boolean remove(Object object) {
            int oldSize = keys.size();
            SequenceHashmap.this.remove(object);
            return keys.size() != oldSize;
        }
    }
}
